package com.mc.websocketjavaandspring.java;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.lang.model.element.VariableElement;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jack3
 */
@ServerEndpoint("/myWs")
@Component
@Slf4j
@EnableScheduling
public class WsServerEndpoint {
    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session.getId(), session);
        log.info("sessionId:{}", session.getId());

    }
    @OnMessage
    public void onMessage(String message, Session session) {
        sessionMap.forEach((k, v) -> {
            v.getAsyncRemote().sendText(message);
        });
        log.info("message:{}", message);
    }
    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session.getId());
    }
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("error:{}", throwable.getMessage());
    }

    public void sendMessage(String message) {
        sessionMap.forEach((k, v) -> {
            try {
                v.getBasicRemote().sendText(message);
            } catch (IOException e) {
                    throw new RuntimeException(e);
            }
        });
    }
    @Scheduled(fixedRate = 5000)
    public void sendMessage() {
        log.info("sendMessage6--------------------------------------------------------------");
        sendMessage("hello world");
    }
}
